<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { useLoginUserStore } from '@/stores/loginUser'
import { addApp, listMyAppVoByPage, listGoodAppVoByPage } from '@/api/appController'
import dayjs from 'dayjs'
import AppCard from '@/components/AppCard.vue'
import HeroSection from '@/components/HeroSection.vue'
import QuickActions from '@/components/QuickActions.vue'

const router = useRouter()
const loginUserStore = useLoginUserStore()

// 用户提示词
const userPrompt = ref('')
const creating = ref(false)

// 我的应用数据
const myApps = ref<API.AppVO[]>([])
const myAppsPage = reactive({
  current: 1,
  pageSize: 6,
  total: 0,
})

// 精选应用数据
const featuredApps = ref<API.AppVO[]>([])
const featuredAppsPage = reactive({
  current: 1,
  pageSize: 6,
  total: 0,
})

// 设置提示词
const setPrompt = (prompt: string) => {
  userPrompt.value = prompt
}

// 优化提示词功能已移除

// 创建应用
const createApp = async () => {
  if (!userPrompt.value.trim()) {
    message.warning('请输入应用描述')
    return
  }

  if (!loginUserStore.loginUser.id) {
    message.warning('请先登录')
    await router.push('/user/login')
    return
  }

  creating.value = true
  try {
    const res = await addApp({
      initPrompt: userPrompt.value.trim(),
    })

    if (res.data.code === 0 && res.data.data) {
      message.success('应用创建成功')
      // 跳转到对话页面
      await router.push(`/app/chat/${res.data.data}`)
    } else {
      message.error('创建失败：' + res.data.message)
    }
  } catch (error) {
    console.error('创建应用失败：', error)
    message.error('创建失败，请重试')
  } finally {
    creating.value = false
  }
}

// 加载我的应用
const loadMyApps = async () => {
  if (!loginUserStore.loginUser.id) {
    return
  }

  try {
    const res = await listMyAppVoByPage({
      pageNum: myAppsPage.current,
      pageSize: myAppsPage.pageSize,
      sortField: 'createTime',
      sortOrder: 'desc',
    })

    if (res.data.code === 0 && res.data.data) {
      myApps.value = res.data.data.records || []
      myAppsPage.total = res.data.data.totalRow || 0
    }
  } catch (error) {
    console.error('加载我的应用失败：', error)
  }
}

// 加载精选应用
const loadFeaturedApps = async () => {
  try {
    const res = await listGoodAppVoByPage({
      pageNum: featuredAppsPage.current,
      pageSize: featuredAppsPage.pageSize,
      sortField: 'priority',
      sortOrder: 'desc',
    })

    if (res.data.code === 0 && res.data.data) {
      featuredApps.value = res.data.data.records || []
      featuredAppsPage.total = res.data.data.totalRow || 0
    }
  } catch (error) {
    console.error('加载精选应用失败：', error)
  }
}

// 查看应用
const viewApp = (appId: string | undefined) => {
  if (appId) {
    router.push(`/app/chat/${appId}`)
  }
}

const viewDeployedApp = (deployKey: string) => {
  window.open(`${import.meta.env.VITE_APP_DEPLOY_DOMAIN}/${deployKey}`, '_blank')
}

// 格式化时间
const formatTime = (time: string | undefined) => {
  if (!time) return ''
  return dayjs(time).format('YYYY-MM-DD')
}

// 页面加载时获取数据
onMounted(() => {
  loadMyApps()
  loadFeaturedApps()
})
</script>

<template>
  <div id="homePageContainer">
    <div id="homePage">
      <!-- 网站标题和描述 -->
      <HeroSection />
      <!-- 用户提示词输入框 -->
      <div class="input-section">
        <a-textarea v-model:value="userPrompt" placeholder="帮我创建个人博客网站" :rows="3" :maxlength="1000" class="prompt-input"
          @pressEnter="createApp" />
        <div class="input-actions">
          <a-button type="primary" size="large" @click="createApp" :loading="creating" @keyup.enter="createApp">
            <template #icon>
              <span>↑</span>
            </template>
          </a-button>
        </div>
      </div>

      <!-- 快捷按钮 -->
      <QuickActions @select="setPrompt" />

      <!-- 我的作品 -->
      <div class="section">
        <h2 class="section-title">我的作品</h2>
        <div class="app-grid">
          <AppCard v-for="app in myApps" :key="app.id" :app="app" @viewApp="viewApp"
            @viewDeployedApp="viewDeployedApp" />
        </div>
        <div class="pagination-wrapper">
          <a-pagination v-model:current="myAppsPage.current" v-model:page-size="myAppsPage.pageSize"
            :total="myAppsPage.total" :show-size-changer="false" :show-total="(total: number) => `共 ${total} 个应用`"
            @change="loadMyApps" />
        </div>
      </div>

      <!-- 精选案例 -->
      <div class="section">
        <h2 class="section-title">精选案例</h2>
        <div class="featured-grid">
          <AppCard v-for="app in featuredApps" :key="app.id" :app="app" :isFeatured="true"
            :defaultAuthorName="'NoCode 官方'" @viewApp="viewApp" @viewDeployedApp="viewDeployedApp" />
        </div>
        <div class="pagination-wrapper">
          <a-pagination v-model:current="featuredAppsPage.current" v-model:page-size="featuredAppsPage.pageSize"
            :total="featuredAppsPage.total" :show-size-changer="false" :show-total="(total: number) => `共 ${total} 个案例`"
            @change="loadFeaturedApps" />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
#homePageContainer {
  padding: 88px 14px 14px;
  width: 100%;

  background-image: linear-gradient(to top, #d9afd9 0%, #97d9e1 100%);
}

#homePage {
  min-height: 100vh;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  color: #333;
  background: transparent;
}

/* 英雄区域通过组件实现 */

.hero-title {
  font-size: 48px;
  font-weight: 700;
  margin: 0 0 16px;
  line-height: 1.2;
}

.hero-description {
  font-size: 18px;
  margin: 0;
  opacity: 0.9;
}

/* 输入区域 */
.input-section {
  position: relative;
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 5px 11px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  width: 65%;
  margin-left: auto;
  margin-right: auto;
}

.prompt-input {
  border-radius: 8px;
  border: none;
  font-size: 16px;
  padding: 16px 60px 16px 16px;
  transition: all 0.3s;
  background: transparent;
}

.prompt-input:focus {
  box-shadow: none;
  outline: none;
}

.input-actions {
  position: absolute;
  bottom: 12px;
  right: 12px;
  display: flex;
  gap: 8px;
  align-items: center;
}

/* 快捷按钮通过组件实现 */

/* 区域标题 */
.section {
  margin-bottom: 60px;
}

.section-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 24px;
}

/* 网格布局样式保留，卡片样式通过组件实现 */
.app-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.featured-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

/* 分页 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .hero-title {
    font-size: 32px;
  }

  .hero-description {
    font-size: 16px;
  }

  .app-grid,
  .featured-grid {
    grid-template-columns: 1fr;
  }

  .quick-actions {
    justify-content: center;
  }
}
</style>
